package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : LeiMingkun
 * @date : 2024-08-06 16:17
 * @description : MyGloBalFilter
 **/
@Component
public class MyGloBalFilter implements Ordered, GlobalFilter {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getPath().toString();
        String ip = request.getRemoteAddress().getAddress().toString();
        if(ip.contains("127.0.0.1")){
            return chain.filter(exchange);
        }
        if(url.contains("/user/user/getLogin")){
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        if(Objects.isNull(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Claims bwie = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();
        Integer id = bwie.get("id", Integer.class);
        Boolean aBoolean = stringRedisTemplate.hasKey("userLogin:" + id);

        Long expire = stringRedisTemplate.getExpire("userLogin:" + id, TimeUnit.MINUTES);
        if(expire<1){
            stringRedisTemplate.expire("userLogin:" + id,1,TimeUnit.MINUTES);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}